/** create by liuhua at 2018年6月5日 下午2:24:14 **/
package com.star.truffle.core.jackson;

import java.io.IOException;

import org.apache.commons.lang3.StringUtils;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;

public class StarXml {

  private XmlMapper xmlMapper;
  private XmlMapper xmlMapper2;

  public StarXml(XmlMapper xmlMapper) {
    this.xmlMapper = xmlMapper;
    this.xmlMapper2 = xmlMapper.copy();
    xmlMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    xmlMapper2.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    xmlMapper2.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
    xmlMapper2.setSerializationInclusion(Include.NON_NULL);  
  }
  
  public <T> String obj2string(T t) {
    try {
      if (null == t) {
        return "<xml></xml>";
      }
      return xmlMapper.writeValueAsString(t);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
  
  public <T> String obj2string(T t, Class<?> serializationView) {
    try {
      return xmlMapper.writerWithView(serializationView).writeValueAsString(t);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
  
  public <T> String obj2stringsnake(T t) {
    try {
      if (null == t) {
        return "<xml></xml>";
      }
      return xmlMapper2.writeValueAsString(t);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
  
  public <T> T str2obj(String xml, TypeReference<T> typeReference) {
    try {
      if(StringUtils.isBlank(xml)) {
        return null;
      }
      return xmlMapper.readValue(xml, typeReference);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
  
  public <T> T str2obj(String xml, Class<T> cls) {
    try {
      if (StringUtils.isBlank(xml)) {
        return null;
      }
      return xmlMapper.readValue(xml, cls);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
  
  public <T> T str2objsnake(String xml, TypeReference<T> typeReference) {
    try {
      if(StringUtils.isBlank(xml)) {
        return null;
      }
      return xmlMapper2.readValue(xml, typeReference);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
}
